package com.yq.ylmall.gateway.filters;

import com.alibaba.fastjson.JSON;
import com.yq.ylmall.common.utils.AuthContextUtil;
import com.yq.ylmall.common.utils.JwtUtils;
import com.yq.ylmall.exception.ServiceException;
import com.yq.ylmall.gateway.config.AuthProperties;
import com.yq.ylmall.model.acl.User;
import com.yq.ylmall.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate<String , String> redisTemplate;
    @Autowired
    private AuthProperties authProperties;
    AntPathMatcher antPathMatcher= new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        log.warn("请求路径:{}",request.getPath());
        log.warn("token：{}", request.getHeaders().getFirst("token"));
        //2.判断是否需要做登录拦截
        if (isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }
        //3.获取用户信息和token
        String adminToken = getAdminToken(request);
        String jsonUser = getJsonUser(adminToken);
        //5.传递用户信息
        log.info("adminToken:{}",adminToken);
        log.info("jsonUser:{}",jsonUser);
        ServerWebExchange swe = exchange.mutate()
                //分发下游请求头
                .request(builder -> builder.header("token",adminToken))
                .request(builder -> builder.header("jsonUser",jsonUser))
                .build();
        //6.放行
        return chain.filter(swe);
    }

    private boolean isExclude(String path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath,path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 获取用户token
     * @param request 请求
     * @return token
     */

    private String getAdminToken(ServerHttpRequest request) {
        String token = "";
        List<String> tokenList = request.getHeaders().get("token");
        if(null  == tokenList && tokenList.isEmpty()) {
            throw new ServiceException(ResultCode.LOGIN_AUTH);
        }
        return token = tokenList.get(0);
    }

    /**
     * 设置线程变量用户
     * @param adminToken 管理员token
     */
    private String getJsonUser(String adminToken) {
        if(StringUtils.isEmpty(adminToken)) {
            throw new ServiceException(ResultCode.LOGIN_AUTH);
        }
        String userInfoJSON = redisTemplate.opsForValue().get("user:login:"+adminToken);
        if(StringUtils.isEmpty(userInfoJSON)) {
            throw new ServiceException(ResultCode.ILLEGAL_TOKEN);
        }
        return userInfoJSON;
    }
}
